package com.knowno.controller;

import com.knowno.dto.AliPay;
import com.knowno.service.TOrderService;
import com.knowno.tools.CommonResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 支付接口
 */
@RestController
@RequestMapping("/alipay")
@Slf4j
public class AliPayController {

    /**
     * 处理支付宝支付请求
     * // ?subject=xxx&traceNo=xxx&totalAmount=xxx
     * @param httpResponse
     * @param aliPay
     * @throws Exception
     */
    @GetMapping("/pay")
    public void pay(AliPay aliPay, HttpServletResponse httpResponse) throws Exception {
        log.info("支付宝controller接受请求参数:{}", aliPay);
        ordersService.pay(aliPay, httpResponse);
    }

    @Autowired
    private TOrderService ordersService;

    /**
     * 处理支付宝回调请求
     *  [注意这里必须是POST请求]
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping("/notify")
    public CommonResponse payNotify(HttpServletRequest request) throws Exception {
        log.info("支付宝controller payNotify :{}", request);
        if(ordersService.payNotify(request) == 1){
            log.info("支付宝controller payNotify  CommonResponse.success() :{}", CommonResponse.success());
            return CommonResponse.success();
        }
        String message = "订单未支付或支付异常，请重新支付！";

        log.info("支付宝controller payNotify  CommonResponse.error(\"-1\",message):{}", CommonResponse.error("-1",message));
        return CommonResponse.error("-1",message);

    }


    @GetMapping("notice")
    public CommonResponse notice() {
        log.info("消息通知 notice ");
        return CommonResponse.success();

    }
}
